// @ts-ignore
import axios from 'axios'
import * as step from '@flow-step/step-toolkit'
import * as path from 'path'
import * as os from 'os'
import { execSync } from 'child_process';
import { exec as originalExec } from 'child_process';
import { promisify } from 'util';
import { mkdir,readFile } from 'fs/promises';
const exec = promisify(originalExec);
import * as fs from 'fs'

import { chdir } from 'process';

import process from "process";
export const SEP = path.sep
export const EOL = os.EOL

export function executeCmdSync(executeCmd: string, args: string[] = []) {
    try {
        const output = execSync(`${executeCmd} ${args.join(' ')}`, { encoding: 'utf-8' });
        // 如果 execSync 执行成功，它将把命令的 stdout 作为字符串返回
        step.info(output);
    } catch (error) {
        // 如果 execSync 抛出错误，error 将带有 stderr 属性
        step.error("executeCmdSync error "+error);
        process.exit(1);
    }
}
// 异步创建软链接
export async function createSymlink(sourcePath: string,symlinkPath: string, linkDir: string) {
    try {
        step.info("createSymlink source:"+sourcePath+",link:"+symlinkPath+"linkDir"+linkDir)

        await createDirectoryIfNotExists(linkDir);
        step.info("createSymlink source:"+sourcePath+",link:"+symlinkPath)
        await fs.promises.symlink(sourcePath, symlinkPath);
    } catch (error) {
        step.info("createSymlink source:"+sourcePath+",link:"+symlinkPath+","+error)
    }
}

async function createDirectoryIfNotExists(dirPath: string): Promise<void> {
    return new Promise((resolve, reject) => {
        fs.mkdir(dirPath, { recursive: true }, (err) => {
            if (err) {
                if (err.code === 'EEXIST') {
                    resolve(); // 目录已存在，视为成功
                } else {
                    reject(new Error(`Create dirPath error ${dirPath}, errorInfo: ${err}`));
                }
            } else {
                step.info(`Create dirPath success ${dirPath}`);
                resolve();
            }
        });
    });
}
export function changeDirectory(targetDir: string) {
    try {
        // Normalize the directory path for cross-platform compatibility
        const dirPath = path.resolve(targetDir);
        // Change the current working directory
        chdir(dirPath);
        step.info(`Changed directory to ${dirPath}`);
    } catch (error) {
        step.error(`Failed to change directory: ${error}`);
        throw error;
    }
}
